#include <windows.h>
#include "DirList.h"
#include "resource.h"

char *GetDesktopPath()
{
	// Get the directory for Windows Desktop. This is
    // stored in the Registry under HKEY_CURRENT_USER\Software\
    // Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\Desktop.
    HKEY hCU;
    DWORD lpType;
    ULONG ulSize = MAX_PATH;
	static char szPath[MAX_PATH];
	const char szRegKey[] = "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders";
	
    if(RegOpenKeyEx(HKEY_CURRENT_USER, szRegKey, 0, KEY_QUERY_VALUE, &hCU) == ERROR_SUCCESS)
    {
		RegQueryValueEx(hCU, "Desktop", NULL, &lpType, (BYTE *)&szPath, &ulSize);
	}
	
	RegCloseKey(hCU);

	return szPath;
}


BOOL CALLBACK DlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	char ach[MAX_PATH];
	UINT uCmd = HIWORD(wParam), uCtrlId = LOWORD(wParam);

	switch(msg)
	{
	case WM_INITDIALOG:
		lstrcpy(ach, GetDesktopPath());

		MakeDirList(GetDlgItem(hwnd, IDC_LIST1), ach);
		return TRUE;

	case WM_COMMAND:
		
		switch(uCtrlId)
		{
		case IDOK: case IDCANCEL:
			EndDialog(hwnd, 0);
			return TRUE;

		case IDC_LIST1:
			if(uCmd == LBN_DIRCHANGE)
			{
				char ach[MAX_PATH];
				DirList_GetPath((HWND)lParam, ach, MAX_PATH);
				SetDlgItemText(hwnd, IDC_EDIT1, ach);
				return TRUE;

			}
			break;
		}
		
		return FALSE;

	case WM_MEASUREITEM:
		if(wParam == IDC_LIST1)
		{
			return DirListMeasure(hwnd, wParam, (MEASUREITEMSTRUCT *)lParam);
		}

		return FALSE;

	case WM_DRAWITEM:
		if(wParam == IDC_LIST1)
		{
			return DirListDraw(hwnd, wParam, (DRAWITEMSTRUCT *)lParam);
		}
		return 0;

	case WM_CLOSE:
		EndDialog(hwnd, 0);
		return TRUE;

	}
	return FALSE;
}

int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR lpCmdLine, int nShowCmd)
{
	DialogBox(hInst, MAKEINTRESOURCE(IDD_DIALOG1), 0, DlgProc);
	return 0;
}